package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

   //根据父类ID查询子类目集合
    @Override
    public List<CategoryDTO> listCategoryByPid(Long pid) {

        //select * from tb_category where parent_id = #{pid}
        List<Category> categoryList = this.list(new QueryWrapper<Category>().eq("parent_id", pid));

        //List<Category>===>List<CategoryDTO>
        return  CategoryDTO.convertEntityList(categoryList);
    }
    //根据分类ID查询商品分类
    @Override
    public CategoryDTO queryCategoryById(Long id) {
        //select * from tb_category where id =#{id}
        Category byId = this.getById(id);
        //Category===>CategoryDto
        return new CategoryDTO(byId);
    }
    //根据分类集合查询商品分类集合
    //TODO :待议
    @Override
    public List<CategoryDTO> listCategoryByIds(List<Long> ids) {
        //mybatis-plus 中自带的方法(自己去探索吧!!!!!)
        return CategoryDTO.convertEntityList(this.listByIds(ids));
    }
    @Autowired
    private CategoryBrandService categoryBrandService;

    //根据品牌ID查询商品分类的集合
    @Override
    public List<CategoryDTO> queryCategoryByBrandId(Long brandId){
        // 1.根据品牌id，查询中间表，得到中间表对象集合
//        List<CategoryBrand> categoryBrandList = categoryBrandService.query().eq("brand_id", brandId).list();
//        if(CollectionUtils.isEmpty(categoryBrandList)){
//            return Collections.emptyList();
//        }
//        // 2.获取分类id集合
//        List<Long> categoryIdList = categoryBrandList.stream()
//                .map(CategoryBrand::getCategoryId).collect(Collectors.toList());
//        // 3.根据分类id集合，查询分类对象集合
//        List<Category> categories = listByIds(categoryIdList);
        List<Long> cids = this.categoryBrandService.query()
                .eq("brand_id", brandId)
                .list().stream()
                .map(CategoryBrand::getCategoryId)
                .collect(Collectors.toList());
        return listCategoryByIds(cids);
        // 4.转换DTO
        //return CategoryDTO.convertEntityList(categories);
    }
}